<template>
  <div class="course-chat">
    <el-card>
      <div slot="header" class="clearfix">
        <span>AI智能问答</span>
        <el-button style="float: right;" @click="$router.back()">返回</el-button>
      </div>
      <div class="chat-history" v-if="history.length">
        <div v-for="(item, idx) in history" :key="idx" class="chat-item">
          <div class="chat-q"><b>Q:</b> {{ item.question }}</div>
          <div class="chat-a"><b>A:</b> {{ item.answer }}</div>
        </div>
      </div>
      <el-empty v-else description="暂无问答记录" />
      <el-form :inline="true" @submit.native.prevent="ask">
        <el-form-item>
          <el-input v-model="question" placeholder="请输入你的问题" style="width: 400px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="ask">提问</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import request from '@/utils/request'
export default {
  name: 'CourseChat',
  data() {
    return {
      question: '',
      history: []
    }
  },
  created() {
    this.fetchHistory()
  },
  methods: {
    fetchHistory() {
      const courseId = this.$route.params.courseId
      request.get(`/api/chat/history/${courseId}`)
        .then(data => { this.history = data })
    },
    ask() {
      if (!this.question) return
      const courseId = this.$route.params.courseId
      request.post(`/api/chat/ask`, { courseId, question: this.question })
        .then(res => {
          this.history.push({ question: this.question, answer: res.answer })
          this.question = ''
        })
    }
  }
}
</script>

<style scoped>
.course-chat { max-width: 700px; margin: 40px auto; }
.chat-history { margin-bottom: 20px; }
.chat-item { margin-bottom: 10px; }
.chat-q { color: #409EFF; }
.chat-a { color: #67C23A; }
</style> 